import React, { useState, useEffect, useRef } from "react";
import styles from "../style/search.module.css";
import leftIcon from "../img/left.png";
import trashIcon from "../img/rubsh.png";
import defaultProductImg from "../img/biudifou.jpg";
import { useNavigate } from "react-router-dom";
import { search, search_del, search_page } from "../api/search";

// 定义搜索记录类型
interface SearchRecord {
  id: number;
  text: string;
  timestamp: number;
}

// 定义商品数据类型
interface Product {
  id: number;
  title: string;
  img: string;
  price: number;
  original_price?: number;
  synopsis: string;
}

// API返回数据类型
interface ApiResponse {
  list?: Product[];
  hot?: string;
  code?: number;
  message?: string;
  data?: {
    list?: Product[];
    hot?: string;
    code?: number;
    message?: string;
  };
}

function SearchPage() {
  const [searchText, setSearchText] = useState(""); // 搜索输入框内容
  const [records, setRecords] = useState<SearchRecord[]>([]); // 搜索历史记录
  const [shopList, setShopList] = useState<Product[]>([]); // 商品列表
  const [hotKeywords, setHotKeywords] = useState<string[]>([]); // 热门关键词
  const [isLoading, setIsLoading] = useState(false); // 加载状态
  const [error, setError] = useState<string | null>(null); // 错误信息
  const [showDeleteButtons, setShowDeleteButtons] = useState(false); // 控制是否显示删除按钮
  const searchTimeout = useRef<NodeJS.Timeout | null>(null); // 防抖计时器
  const navigate = useNavigate(); // 路由导航
  const user = JSON.parse(localStorage.getItem("user") || "null"); // 用户信息

  // 组件加载时从本地存储读取搜索历史
  useEffect(() => {
    try {
      const saved = localStorage.getItem("searchHistory");
      if (saved) {
        const parsedRecords = JSON.parse(saved);
        // 验证数据格式是否正确
        if (
          Array.isArray(parsedRecords) &&
          parsedRecords.every((item) => item.id && item.text)
        ) {
          setRecords(parsedRecords);
        }
      }
    } catch (err) {
      console.error("读取本地存储失败:", err);
      localStorage.removeItem("searchHistory");
    }
  }, []);

  // 当搜索记录变化时保存到本地存储
  useEffect(() => {
    if (records.length > 0) {
      // 清除之前的防抖计时器
      if (searchTimeout.current) clearTimeout(searchTimeout.current);
      // 设置新的防抖计时器
      searchTimeout.current = setTimeout(() => {
        localStorage.setItem(
          "searchHistory",
          JSON.stringify(records.slice(0, 10))
        );
      }, 300);
    }
    // 组件卸载时清除计时器
    return () => {
      if (searchTimeout.current) clearTimeout(searchTimeout.current);
    };
  }, [records]);

  // 获取热门关键词
  useEffect(() => {
    const fetchHotKeywords = async () => {
      try {
        setIsLoading(true);

        // ==================搜索页面接口==================
        const res = await search_page({
          user_id: user?.data?.id || 0,
          timeout: 5000, // 设置请求超时时间
        });

        if (res.data?.code === 200 && res.data.hot) {
          // 处理热门关键词数据
          const keywords = res.data.hot
            .split(",")
            .map((k: string) => k.trim())
            .filter(Boolean);

          setHotKeywords(keywords);
          localStorage.setItem("hotKeywords", JSON.stringify(keywords));
        } else {
          throw new Error("获取热门关键词失败：响应格式不符合预期");
        }
      } catch (error) {
        console.error("获取热门搜索失败:", error);
        // 使用默认值
        setHotKeywords(["便利贴", "铅笔", "印刷纸", "记号笔", "复写笔"]);
      } finally {
        setIsLoading(false);
      }
    };

    fetchHotKeywords();
  }, [user?.data?.id]);

  // 搜索防抖处理
  const debouncedSearch = useRef<(text: string) => void>();
  useEffect(() => {
    debouncedSearch.current = (text: string) => {
      // 清除之前的计时器
      if (searchTimeout.current) clearTimeout(searchTimeout.current);
      // 设置新的计时器
      searchTimeout.current = setTimeout(async () => {
        console.log('准备执行搜索，搜索文本:', text); // 添加日志
        
        if (!text.trim()) {
          console.log('搜索文本为空，取消搜索');
          return;
        }

        try {
          setIsLoading(true);

          //========================== 搜索接口==================
          // 关键修改：添加搜索文本参数
          const searchParams = {
            user_id: user?.data?.id || 0,
            text: text.trim(), // 添加搜索关键词参数
            timeout: 10000,
          };
          
          console.log('搜索参数:', searchParams); // 添加日志
          
          const res = await search(searchParams);
          
          console.log('搜索响应:', res); // 添加日志

          // 处理返回的商品数据
          const rawList = res.data.list || res.data.data?.list || [];
          const processedList = rawList.map((item: Product) => ({
            id: item.id || Date.now(),
            title: item.title || "未命名商品",
            img: item.img ? `${item.img}` : defaultProductImg,
            price: Number(item.price) || 0,
            original_price: item.original_price
              ? Number(item.original_price)
              : undefined,
            synopsis: item.synopsis || "暂无商品描述",
          }));

          console.log('处理后的商品列表:', processedList); // 添加日志
          
          setShopList(processedList);
        
          // 添加到搜索历史
          const newRecord: SearchRecord = {
            id: Date.now(),
            text: text.trim(),
            timestamp: Date.now(),
          };

          setRecords((prev) =>
            [
              newRecord,
              ...prev.filter(
                (item) =>
                  item.text.toLowerCase() !== newRecord.text.toLowerCase()
              ),
            ].slice(0, 10)
          );
        } catch (err: any) {
          console.error("搜索失败:", err);

          // 错误处理
          if (err.code === "ECONNABORTED") {
            setError("请求超时，请稍后重试");
          } else if (err.response) {
            setError(err.response.data.message || "搜索失败");
          } else if (err.request) {
            setError("网络连接异常");
          } else {
            setError("未知错误");
          }
          setShopList([]);
        } finally {
          setIsLoading(false);
        }
      }, 500);
    };
  }, [user?.data?.id]);

  // 输入框变化处理
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    console.log('输入框变化，新值:', value); // 添加日志
    setSearchText(value);
    setError(null);
  };

  // 执行搜索
  const handleSearch = () => {
    console.log('执行搜索按钮点击，当前搜索文本:', searchText); // 添加日志
    
    if (searchTimeout.current) clearTimeout(searchTimeout.current);
    
    // 直接使用 searchText 状态
    if (searchText.trim()) {
      debouncedSearch.current?.(searchText);
    } else {
      console.log('搜索文本为空，不执行搜索');
      setError("请输入搜索内容");
    }
  };

  // 删除单个搜索记录
  const handleDeleteRecord = (id: number) => {
    setRecords((prev) => prev.filter((item) => item.id !== id));
  };

  // 清空所有搜索记录
  const handleClearAll = () => {
    if (window.confirm("确定要清空所有搜索记录吗？")) {
      setRecords([]);
      setShowDeleteButtons(false);
    }
  };

  // 切换删除按钮显示状态
  const toggleDeleteButtons = () => {
    setShowDeleteButtons(!showDeleteButtons);
  };

  // 商品点击跳转详情页
  const handleItemClick = (id: number) => {
    localStorage.setItem("productId", id.toString());
    navigate("/detail");
  };

  // 渲染搜索历史记录
  const renderHistory = () => {
    if (!records.length) return null;

    return (
      <section className={styles.historySection}>
        <div className={styles.sectionHeader}>
          <h3>历史搜索</h3>
          <div className={styles.clearControls}>
            {showDeleteButtons ? (
              <div className={styles.buttonGroup}>
                <button
                  onClick={handleClearAll}
                  className={styles.clearAllButton}
                >
                  全部删除
                </button>
                <button
                  onClick={toggleDeleteButtons}
                  className={styles.finishButton}
                >
                  完成
                </button>
              </div>
            ) : (
              <button
                onClick={toggleDeleteButtons}
                aria-label="显示删除按钮"
                className={styles.editButton}
              >
                <img src={trashIcon} alt="删除" className={styles.trashIcon} />
              </button>
            )}
          </div>
        </div>
        <div className={styles.historyList}>
          {records.map((item) => (
            <div key={item.id} className={styles.historyItem}>
              <span
                className={styles.historyText}
                onClick={() => {
                  console.log('点击历史记录，设置搜索文本:', item.text);
                  setSearchText(item.text);
                  handleSearch();
                }}
              >
                {item.text}
              </span>
              {showDeleteButtons && (
                <button
                  className={styles.deleteButton}
                  onClick={(e) => {
                    e.stopPropagation();
                    handleDeleteRecord(item.id);
                  }}
                  aria-label="删除此记录"
                >
                  ×
                </button>
              )}
            </div>
          ))}
        </div>
      </section>
    );
  };

  // 渲染热门关键词
  const renderHotKeywords = () => {
    if (isLoading && !hotKeywords.length) {
      return <div className={styles.loading}>加载中...</div>;
    }

    if (error && !hotKeywords.length) {
      return <div className={styles.error}>{error}</div>;
    }

    // 定义默认热门关键词
    const defaultHotKeywords = ["便利贴", "铅笔", "印刷纸", "记号笔", "复写笔"];

    return (
      <>
        <h3>热门搜索</h3>
        <div className={styles.hotList}>
          {hotKeywords.length
            ? hotKeywords.map((keyword, index) => (
                <div
                  key={index}
                  className={styles.hotItem}
                  onClick={() => {
                    console.log('点击热门关键词，设置搜索文本:', keyword);
                    setSearchText(keyword);
                    handleSearch();
                  }}
                >
                  {keyword}
                </div>
              ))
            : defaultHotKeywords.map((keyword, index) => (
                <div
                  key={index}
                  className={styles.hotItem}
                  onClick={() => {
                    console.log('点击默认热门关键词，设置搜索文本:', keyword);
                    setSearchText(keyword);
                    handleSearch();
                  }}
                >
                  {keyword}
                </div>
              ))}
        </div>
      </>
    );
  };

  // 渲染商品列表
  const renderProductList = () => {
    if (isLoading && !shopList.length) {
      return <div className={styles.loading}>搜索中...</div>;
    }

    if (error && !shopList.length) {
      return <div className={styles.error}>{error}</div>;
    }

    if (!shopList.length) {
      return <div className={styles.emptyState}>暂无相关商品</div>;
    }

    return (
      <div className={styles.shop}>
        {shopList.map((product) => (
          <div
            key={product.id}
            className={styles.shop_item}
            onClick={() => handleItemClick(product.id)}
          >
            <img src={product.img} alt={product.title} />
            <p>{product.title}</p>
            <span>{product.synopsis}</span>
            <div className={styles.items}>
              <p>￥{Number(product.price).toFixed(2)}</p>
              {product.original_price && (
                <del>￥{Number(product.original_price).toFixed(2)}</del>
              )}
            </div>
          </div>
        ))}
      </div>
    );
  };

  return (
    <div className={styles.container}>
      {/* 搜索栏 */}
      <div className={styles.searchBar}>
        <div className={styles.backButton}>
          <img src={leftIcon} onClick={() => navigate(-1)} alt="返回" />
        </div>
        <div className={styles.searchInput}>
          <input
            type="text"
            placeholder="输入商家、商品名称"
            value={searchText}
            onChange={handleInputChange}
            onKeyPress={(e) => e.key === "Enter" && handleSearch()}
            aria-label="搜索输入框"
          />
          {searchText && (
            <button
              className={styles.clearInput}
              onClick={() => setSearchText("")}
              aria-label="清空输入"
            >
              ×
            </button>
          )}
        </div>
        <button
          className={styles.searchButton}
          onClick={handleSearch}
          disabled={isLoading || !searchText.trim()}
          aria-label="开始搜索"
        >
          {isLoading ? "搜索中..." : "搜索"}
        </button>
      </div>

      {/* 渲染搜索历史 */}
      {renderHistory()}

      {/* 渲染热门关键词 */}
      <section className={styles.hotSection}>{renderHotKeywords()}</section>

      {/* 渲染商品列表 */}
      <section className={styles.productList}>{renderProductList()}</section>
    </div>
  );
}

export default SearchPage;